package io.modifier.basic.compose.widget.aowsome

import android.content.res.Configuration
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.DefaultShadowColor
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.lerp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.util.lerp
import com.wquick.base.R
import io.modifier.basic.compose.theme.AppTheme
import kotlin.math.absoluteValue

// https://juejin.cn/post/7457774343293763584

data class MovieItem(val name: String, val resId: Int, val description: String = "")

val movieData = arrayOf(
    MovieItem("Robot Dreams", R.drawable.compose_views_refresh_layout_loading, "DOG lives in Manhattan and he's tired of being alone. One day he decides to build himself a robot, a companion. Their friendship blossoms, until they become inseparable, to the rhythm of 80's NYC. One summer night, DOG, with great sadness, is forced to abandon ROBOT at the beach. Will they ever meet again?"),
    MovieItem("Anatomy of a Fall", R.drawable.compose_views_refresh_layout_loading, description = "The story begins when Samuel is found dead in the snow outside the isolated chalet where he lived with his wife Sandra, a German writer, and their partially-sighted 11-year-old son Daniel. An investigation leads to a conclusion of \"suspicious death\": it's impossible to know for sure whether he took his own life or was killed. Sandra is indicted, and we follow her trial which pulls the couple's relationship apart. Daniel is caught in the middle: between the trial and their home life, doubts take their toll on the mother-son relationship."),
    MovieItem("Frances Ha", R.drawable.compose_views_refresh_layout_loading, description = "Frances lives in New York, but she doesn't really have an apartment. Frances is an apprentice for a dance company, but she's not really a dancer. Frances has a best friend named Sophie, but they aren't really speaking anymore. Frances throws herself headlong into her dreams, even as their possible reality dwindles. Frances wants so much more than she has but lives her life with unaccountable joy and lightness."),
    MovieItem("Pulp Fiction", R.drawable.compose_views_refresh_layout_loading, description = "Jules Winnfield (Samuel L. Jackson) and Vincent Vega (John Travolta) are two hitmen who are out to retrieve a suitcase stolen from their employer, mob boss Marsellus Wallace (Ving Rhames). Wallace has also asked Vincent to take his wife Mia (Uma Thurman) out a few days later when Wallace himself will be out of town. Butch Coolidge (Bruce Willis) is an aging boxer who is paid by Wallace to lose his fight. The lives of these seemingly unrelated people are woven together comprising of a series of funny, bizarre and uncalled-for incidents."),
    MovieItem("The Shining", R.drawable.compose_views_refresh_layout_loading, description = "After landing a job as an off-season caretaker, Jack Torrance, an aspiring author and recovering alcoholic, drags his wife Wendy and gifted son Danny to snow-covered Colorado's secluded Overlook Hotel. However, writer's block prevents Jack from pursuing a new writing career. Everything has its time, however. First, the manager must give Jack a grand tour. Then, Mr Hallorann, the facility's aging chef, chats with Danny about rare psychic gifts. The mysterious employee also warns the boy about the cavernous hotel's abandoned rooms. Room 237, especially, is off-limits. That's all very well, but Jack is gradually losing his mind. After all, strange occurrences and blood-chilling visions have trapped the family in a silent gargantuan prison hammered by endless snowstorms. And now, incessant voices inside Jack's head demand sacrifice. However, is Jack capable of murder?"),
)
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun MainPage(modifier: Modifier = Modifier) {

    val pagerState = rememberPagerState(pageCount = { movieData.size })

    Crossfade(
        targetState = pagerState.currentPage,
        animationSpec = tween(500),
        label = "background image cross fade"
    ) { currentPage ->
        val pageOffset = pagerState.currentPageOffsetFraction // ADD

        Image(
            modifier = Modifier
                .fillMaxSize()
                .graphicsLayer {
                    scaleX = lerp(1f, 1.1f, pageOffset.absoluteValue) // ADD
                    scaleY = lerp(1f, 1.1f, pageOffset.absoluteValue) // ADD
                    translationY = lerp(0f, -20f, pageOffset.absoluteValue) // ADD
                }
                .drawWithCache {
                    val gradient = Brush.verticalGradient(
                        colors = listOf(Color.Transparent, Color.White),
                        startY = 0f,
                        endY = size.height / 1.5f
                    )
                    onDrawWithContent {
                        drawContent()
                        drawRect(gradient, blendMode = BlendMode.Lighten)
                    }
                },
            painter = painterResource(movieData[currentPage].resId),
            contentDescription = "",
            contentScale = ContentScale.FillWidth,
            alignment = Alignment.TopCenter
        )
    }

    HorizontalPager(
        state = pagerState,
        modifier = modifier.fillMaxSize(),
        verticalAlignment = Alignment.Bottom,
        pageSpacing = 20.dp,
        contentPadding = PaddingValues(horizontal = 50.dp)
    ) { page ->
        val pageOffset = pagerState.calculateCurrentOffsetForPage(page)
        MovieCard(
            modifier = Modifier
                .padding(bottom = lerp(96.dp, 56.dp, pageOffset.absoluteValue))
                .width(260.dp)
                .height(480.dp)
                .graphicsLayer {
                    clip = true
                    shape = RoundedCornerShape(130.dp)
                    shadowElevation = 30f
                    spotShadowColor = DefaultShadowColor.copy(alpha = 0.5f)
                    ambientShadowColor = DefaultShadowColor.copy(alpha = 0.5f)
                    scaleY = lerp(1f, 0.9f, pageOffset.absoluteValue)
                }
                .background(color = Color.White)
                .padding(top = 32.dp, start = 32.dp, end = 32.dp),
            page = page,
            movie = movieData[page]
        )
    }



}

@OptIn(ExperimentalFoundationApi::class)
private fun PagerState.calculateCurrentOffsetForPage(page: Int): Float {
    return (currentPage - page) + currentPageOffsetFraction
}

@Composable
fun MovieCard(modifier: Modifier, page: Int, movie: MovieItem) {
    Box(modifier = modifier) {
        Column(
            modifier = Modifier
                .align(Alignment.TopCenter)
                .fillMaxWidth()
        ) {
            Image(
                painter = painterResource(movie.resId),
                contentDescription = "",
                contentScale = ContentScale.FillBounds,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(290.dp)
                    .clip(RoundedCornerShape(100.dp))
            )
            Text(
                text = movie.name,
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center,
                modifier = Modifier
                    .padding(16.dp)
                    .align(Alignment.CenterHorizontally)
            )
        }
        BookNow(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .fillMaxWidth()
                .height(60.dp)
                .clip(RoundedCornerShape(50.dp))
                .background(Color.Black)
        )
    }
}

@Composable
fun BookNow(modifier: Modifier = Modifier) {
    Box(
        modifier = modifier,
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "BOOK NOW",
            color = Color.White,
            fontSize = 12.sp
        )
    }
}




@Composable
private fun PreviewPager() {
    AppTheme {
        MainPage()
    }
}

@Preview(backgroundColor = 0xFF121212, showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO)
@Composable
private fun PreviewLightPager() {
    PreviewPager()
}

@Preview(backgroundColor = 0xFFf5f5f5, showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun PreviewDarkPager() {
   PreviewPager()
}